package com.chj.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chj.constants.Constants;
import com.chj.entity.ECarModel;
import com.chj.entity.NetWork;
import com.chj.entity.NetWorkDataGridJson;
import com.chj.entity.Order;
import com.chj.entity.Park;
import com.chj.entity.ParkModel;
import com.chj.entity.User;
import com.chj.service.ECarService;
import com.chj.service.MessageService;
import com.chj.service.NetWorkServcie;
import com.chj.service.OrderService;
import com.chj.service.ParkService;
import com.chj.util.DateUtil;
import com.chj.util.GenerateSequenceUtil;
import com.chj.util.JSONUtils;

@Controller
@RequestMapping("ecarcharge")
public class ECarChargeController {

    @Resource
    private NetWorkServcie netWorkServcie;

    @Resource
    private ParkService parkService;

    @Resource
    private ECarService eCarService;
    
    @Resource
    private OrderService orderService;

    @Resource
    private MessageService messageService;

    // 我要充电页面
    @RequestMapping("we_need_charge")
    public String weNeedCharge() {
        return "ecarcharge/we_need_charge";
    }

    @RequestMapping(value = "test")
    public String Test() {
        return "ecarcharge/test";
    }

    @RequestMapping(value = "json")
    @ResponseBody
    public JSONObject getJson() {

        List<NetWork> netWorkList = netWorkServcie.getNetWorkAllList();

        NetWorkDataGridJson<NetWork> jsonList = new NetWorkDataGridJson<NetWork>();

        jsonList.setTotal(netWorkList.size());
        jsonList.setRows(netWorkList);

        JSONObject jsonObj = JSONUtils.getJsonObject(jsonList);

        return jsonObj;
    }

    @RequestMapping(value = "queryNetwork",produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject queryNetwork(HttpServletRequest  request
                                 , HttpServletResponse response
                                 , @RequestParam(value="netWorkStr") String netWorkStr) {

        Map<String, Object> queryMap = JSONUtils.parseJsonStr(netWorkStr);

        List<NetWork> netWorkList = netWorkServcie.getNetWorkListBy(queryMap,0,0);

        Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap.put("netWorkList", netWorkList);

        return JSONUtils.getJsonObject(resultMap);
    }

    @RequestMapping(value="query_network/{netWorkId}")
    public ModelAndView selectPark(@PathVariable("netWorkId") String netWorkId){

        Map<String, Object> map = new HashMap<String, Object>();

        NetWork netWork = netWorkServcie.getNetWork(netWorkId);

        map.put("netWork", netWork);

        List<Park> parkList = parkService.getParkListByNetWorkId(netWorkId);

        map.put("parkList", parkList);

        //跳转页面并且查询网点车位
        return new ModelAndView("ecarcharge/select_park",map);
    }

    @RequestMapping(value = "query_network_park/{networkId}")
    @ResponseBody
    public JSONObject queryNetworkPark(HttpServletRequest  request
            					     , HttpServletResponse response
            					     , @PathVariable("networkId") String networkId
            					     , @RequestParam(value="netWorkParkStr") String netWorkParkStr){
    	
    	Map<String, Object> queryMap = JSONUtils.parseJsonStr(netWorkParkStr);

    	List<ParkModel> parkModelList = parkService.getParkListAndStatus(networkId, queryMap);

    	int chargeNum = 0;
    	for (ParkModel parkModel : parkModelList) {
			if (parkModel.isParkStatus()){
				continue;
			} else {
				chargeNum ++;
			}
		}

    	Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap.put("parkModelList", parkModelList);
        resultMap.put("chargeNum"    , chargeNum );

    	return JSONUtils.getJsonObject(resultMap);
    }

    @RequestMapping(value = "select_ecar")
    public ModelAndView parkSelectEcar(HttpServletRequest  request
                                     , HttpServletResponse response
                                     , String parkId
                                     , String networkId
                                     , String chargeTimeBegin
                                     , String chargeTimeEnd){

        Map<String, Object> model = new HashMap<String, Object>();

        //获取网点信息
        NetWork netWork = netWorkServcie.getNetWork(networkId);
        model.put("netWork", netWork);
        //获取用户信息
        User user = (User)request.getSession().getAttribute(Constants.LOGIN_USER);
        model.put("user", user);
        //获取车位信息
        Park park = parkService.getParkById(parkId);
        model.put("park", park);
        //获取汽车信息
        List<ECarModel> eCarModelList = eCarService.getECarsByUserIdAndBeginAndEnd(user.getUserPk(),chargeTimeBegin,chargeTimeEnd);
        //获取时间信息
        model.put("chargeTimeBegin", chargeTimeBegin);
        model.put("chargeTimeEnd"  , chargeTimeEnd);

        model.put("eCarModelList", JSONUtils.getJsonArray(eCarModelList).toString());

        return new ModelAndView("ecarcharge/select_ecar", model);
    }

    @RequestMapping(value = "create_order")
    public ModelAndView createOrder(HttpServletRequest  request
                                  , HttpServletResponse response
                                  , String ecarId
                                  , String parkId
                                  , String networkId
                                  , String chargeTimeBegin
                                  , String chargeTimeEnd){

        BigDecimal orderTimeLong = DateUtil.getSub(DateUtil.toDate(chargeTimeBegin), DateUtil.toDate(chargeTimeEnd));
        User user = (User)request.getSession().getAttribute(Constants.LOGIN_USER);

        Park park = parkService.getParkById(parkId);

        Order order = new Order();
        order.setOrderPk(GenerateSequenceUtil.getUUID());
        order.setOrderId(GenerateSequenceUtil.getOrderNo());
        order.setUserId(user.getUserPk());
        order.setEcarId(ecarId);
        order.setParkId(parkId);
        order.setNetworkId(networkId);
        order.setParkPrice(park.getParkPrice());
        order.setParkPayMoney(order.getParkPrice().multiply(orderTimeLong));
        order.setOrderStatus(0);
        order.setCompleteStatus(0);
        order.setPayStatus(0);
        order.setPayDate(null);
        order.setOrderBeginTime(DateUtil.toDate(chargeTimeBegin));
        order.setOrderEndTime(DateUtil.toDate(chargeTimeEnd));
        order.setOrderTimeLong(orderTimeLong);
        order.setOrderPaysuccessId("");
        order.setOrderCallbackId("");
        order.setCreateDate(new Date());
        order.setModifyDate(new Date());
        order.setDeleteDate(new Date());
        order.setStatus(1);

        Map<String, Object> map = new HashMap<String, Object>();

        if (orderService.addOrder(order) > 0) {

            map.put("order", order);
            map.put("park", park);
            map.put("network", netWorkServcie.getNetWork(networkId));
            map.put("ecar", eCarService.getECar(ecarId));
            map.put("chargeTimeBegin", chargeTimeBegin);
            map.put("chargeTimeEnd", chargeTimeEnd);
            messageService.sendMsg(user.getUserPk(), "创建订单成功！");
            return new ModelAndView("ecarcharge/ecarcharge_to_pay",map);
        } else {

            map.put("errorMsg", "出现系统错误，请重新尝试");
            return new ModelAndView("ecarcharge/add_order_fail",map);
        }
    }

    @RequestMapping(value = "pay_for_order")
    public ModelAndView payForOrder(HttpServletRequest  request
                                  , HttpServletResponse response
                                  , String orderPk){

        if(orderService.payForOrder(orderPk) > 0){
            User user = (User)request.getSession().getAttribute(Constants.LOGIN_USER);
            messageService.sendMsg(user.getUserPk(), "支付成功");
            return new ModelAndView("person/person_order_manager",null);
        } else {
            return new ModelAndView("commons/unauthorized",null);
        }
    }

    @RequestMapping(value = "cancel_for_order")
    public ModelAndView cancelForOrder(HttpServletRequest  request
                                     , HttpServletResponse response
                                     , String              orderPk){
        //取消订单操作
        return new ModelAndView("commons/unauthorized",null);
    }
}
